/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dubbo.remoting.exchange.support.header;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.Transporters;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.ExchangeHandler;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchanger;
import org.apache.dubbo.remoting.transport.DecodeHandler;

/**
 * DefaultMessenger
 *
 *
 */
public class HeaderExchanger implements Exchanger {

    public static final String NAME = "header";

    @Override
    public ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException {
        // 这里的HeaderExchangeClient是对目标服务的一个统一封装，因为目标服务可能是netty，也可能是mina，
        // 这里将其统一封装为Client对象。另外，这里还会启动一个定时器，以对目标服务进行心跳检测和重连
        return new HeaderExchangeClient(
            Transporters.connect(url,
                new DecodeHandler(new HeaderExchangeHandler(handler))), true);
    }

    @Override
    public ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException {
        // 这里的HeaderExchangeServer是对目标服务的一个统一封装，比如所Transporter层返回的Server可能是
        // NettyServer，也可能是MinaServer。而HeaderExchangeServer只面向统一的Server接口，并且封装了
        // 相应的操作，不过主要有一点时，HeaderExchangeServer也添加了心跳功能，即定时检测目标连接是否在指定
        // 时间段内进行了读写操作，如果没有，则会调用对应连接的close()方法关闭连接
        return new HeaderExchangeServer(
            // Transporter是传输层，其作用主要是根据配置文件中指定所使用的服务，比如netty或mina，将其封装
            // 为统一的Server对象
            Transporters.bind(
                url,
                new DecodeHandler(new HeaderExchangeHandler(handler))
            )
        );
    }

}
